jQuery中 bind delegate click on都是啥?

.bind( eventType [, eventData ], handler )

1
2
3
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
  • 给匹配到的元素绑定事件
  • 对于动态添加的元素,不会绑定事件。

.delegate( selector, eventType, eventData, handler )

1
2
3
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
  • 对于动态添加的元素,会绑定事件。

.click( handler )

1
2
3
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
  • 给元素绑定单击事件
  • 对于动态添加的元素,不会绑定事件。

.on( events [, selector ] [, data ], handler )

1
2
3
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
  • 对于动态添加的元素,会绑定事件
  • jQuery源码中.bind()、.delegate()方法都是通过.on()方法实现的。
如果用的jQuery版本是1.7+的话,建议使用.on()方法绑定事件。